<template>
  <div class="flex">
    <!-- 左侧 -->
    <div class="flex flex-col shrink-0 h-[100vh] border-r">
      <Header v-if="!foldMenu" />
      <div class="flex-grow">
        <S-menu
          v-if="showMenu"
          :menu_list="menuStore.menu_list_hasPermission"
          :collapse="foldMenu"
        />
      </div>
    </div>
    <!-- 右侧 -->
    <div class="flex-grow flex flex-col h-[100vh]">
      <div class="flex justify-between m-3">
        <div class="flex items-center">
          <S-icon
            v-if="foldMenu"
            @click="foldMenuToggle"
            class="cursor-pointer"
            icon="ant-design:menu-unfold-outlined"
          />
          <S-icon
            v-else
            @click="foldMenuToggle"
            class="cursor-pointer"
            icon="ant-design:menu-fold-outlined"
          />
          <S-breadcrumb class="ml-4" :menu_list="menuStore.menu_list" />
        </div>
        <div class="flex items-center">
          <S-fullScreen class="mr-2" />
          <el-dropdown placement="bottom-end">
            <el-avatar :size="24" :src="currentUser?.avatar">
              {{ userName ? userName[0].toUpperCase() : "" }}
            </el-avatar>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="openEditInfo"
                  >修改资料</el-dropdown-item
                >
                <el-dropdown-item @click="openEditPassword"
                  >修改密码</el-dropdown-item
                >
                <el-dropdown-item @click="showPermission"
                  >当前权限</el-dropdown-item
                >
                <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <div class="m-3 mt-0 flex-grow flex flex-col">
        <S-pageTabs
          v-if="showMenu"
          :menu_list="menuStore.menu_list"
          homePath="/"
        >
          <slot class="w-full h-full" />
        </S-pageTabs>
      </div>
    </div>
    <!-- 修改密码的弹窗 -->
    <el-dialog
      title="修改密码"
      v-model="editPassword_dialogVisible"
      width="40%"
    >
      <S-form
        :Model="editPassword_Model"
        :colNum="1"
        :local_save="editPassword_local_save"
        :cancel="
          () => {
            editPassword_dialogVisible = false;
          }
        "
      >
      </S-form>
    </el-dialog>
    <!-- 当前权限的弹窗 -->
    <el-dialog
      title="当前权限"
      v-model="showPermission_dialogVisible"
      width="600"
    >
      <Permission
        :handle_permission="currentUser.handle_permissionList"
        :menu_permission="menuStore.menu_list_hasPermission"
        :ifSuperAdmin="currentUser.ifSuperAdmin"
      />
    </el-dialog>
    <S-msgWin :msg="callbackMessage" />
  </div>
</template>
<script lang="ts" setup>
const callbackMessage = useCallbackMessage();
const currentUser = useCurrentUserStore().currentUser;
// 加载菜单
const menuStore = useMenuStore();

const userName =
  currentUser?.nickName || currentUser?.name || currentUser?.account;

const foldMenu = ref(false);
const showMenu = ref(true);

const foldMenuToggle = (val: boolean) => {
  if (typeof val === "boolean") {
    foldMenu.value = val;
  } else {
    foldMenu.value = !foldMenu.value;
  }
  reloadMenu();
};

const reloadMenu = async () => {
  showMenu.value = false;
  await nextTick();
  showMenu.value = true;
};

menuStore.getMenu_all(reloadMenu);

const editPassword_dialogVisible = ref(false);

const editPassword_Model = {
  newPassword: {
    label: "新密码",
    type: "password",
    require: true,
  },
  newPassword_confirm: {
    label: "密码确认",
    type: "password",
    formRules: [
      { required: true, message: "请再次输入新密码", trigger: "blur" },
    ],
  },
};

const openEditPassword = () => {
  editPassword_dialogVisible.value = true;
};

const editPassword_local_save = async (formData: any) => {
  let error_msg = "";
  if (formData.newPassword !== formData.newPassword_confirm) {
    error_msg = "两次密码输入不一致";
  }
  if (error_msg) {
    callbackMessage.value = {
      show: true,
      valid: false,
      content: error_msg,
    };
    return;
  }
  try {
    await useFetch(`/api/user/${currentUser._id}`, {
      method: "PATCH",
      query: {
        handleType: "editPassword",
        newPassword: formData.newPassword,
      },
    });
    callbackMessage.value = {
      show: true,
      valid: true,
      content: "操作成功",
    };
    editPassword_dialogVisible.value = false;
  } catch (e: any) {
    callbackMessage.value = {
      show: true,
      valid: false,
      content: e.data.message,
    };
  }
};

const openEditInfo = () => {
  useRouter().push("/me/editInfo");
};

const showPermission_dialogVisible = ref(false);

const showPermission = () => {
  showPermission_dialogVisible.value = true;
};

const logout = async () => {
  try {
    // 清除 cookie 中的 token
    useCookie("token").value = null;
    // 关闭tabs
    usePageTabsStore().closeAllTabs();
    // 清空菜单
    useMenuStore().clearMenu();
    // 记录日志
    useLog("登出");
    // 重定向到登录页面
    useRouter().push("/user/login");
  } catch (error) {
    console.error("登出失败:", error);
  }
};
</script>
